<template>
  <div class="login-container">
    <div class="login-background">
      <div class="background-overlay"></div>
    </div>
    
    <div class="login-content">
      <div class="login-card">
        <div class="login-header">
          <div class="logo">
            <img src="/logo.svg" alt="AI Market" />
            <h1>AI Market</h1>
          </div>
          <p class="subtitle">欢迎回来，请登录您的账户</p>
        </div>
        
        <a-form
          :model="loginForm"
          :rules="rules"
          @finish="handleLogin"
          @finishFailed="handleLoginFailed"
          layout="vertical"
          class="login-form"
        >
          <a-form-item name="userAccount" label="用户名">
            <a-input
              v-model:value="loginForm.userAccount"
              size="large"
              placeholder="请输入用户名"
              :prefix="h(UserOutlined)"
            />
          </a-form-item>
          
          <a-form-item name="userPassword" label="密码">
            <a-input-password
              v-model:value="loginForm.userPassword"
              size="large"
              placeholder="请输入密码"
              :prefix="h(LockOutlined)"
            />
          </a-form-item>
          
          <a-form-item>
            <div class="login-options">
              <a-checkbox v-model:checked="rememberMe">记住我</a-checkbox>
              <a href="#" class="forgot-password">忘记密码？</a>
            </div>
          </a-form-item>
          
          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              size="large"
              :loading="loading"
              class="login-button"
              block
            >
              登录
            </a-button>
          </a-form-item>
          
          <div class="register-link">
            还没有账户？
            <router-link to="/register" class="register-text">立即注册</router-link>
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { login, getUserInfo } from '@/api/auth'
import { eventBus, EVENT_TYPES } from '@/utils/eventBus'
import type { LoginRequest, UserVO } from '@/types/api'

const router = useRouter()
const loading = ref(false)
const rememberMe = ref(false)

// 表单数据
const loginForm = reactive<LoginRequest>({
  userAccount: '',
  userPassword: ''
})

// 表单验证规则
const rules = {
  userAccount: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  try {
    loading.value = true
    const response = await login(loginForm)
    
    if (response.code === 0) {
      // response.data 现在是 SaTokenInfo 对象
      const tokenInfo = response.data
      
      // 保存token信息到localStorage
        localStorage.setItem('tokenName', tokenInfo.tokenName)
        localStorage.setItem('tokenValue', tokenInfo.tokenValue)
        localStorage.setItem('userId', tokenInfo.loginId.toString())
        
        // 登录成功后立即获取用户信息
        try {
          const userInfoResponse = await getUserInfo()
          if (userInfoResponse.code === 0) {
            // 保存用户信息到localStorage
            localStorage.setItem('userInfo', JSON.stringify(userInfoResponse.data))
            
            // 触发用户登录事件，通知其他组件更新
            console.log('触发用户登录事件')
            eventBus.emit(EVENT_TYPES.USER_LOGIN)
            
            message.success('登录成功')
            
            // 跳转到首页
            router.push('/')
          } else {
            message.error('获取用户信息失败，但登录成功')
            router.push('/')
          }
        } catch (userInfoError) {
          console.error('获取用户信息错误:', userInfoError)
          message.error('获取用户信息失败，但登录成功')
          // 即使获取用户信息失败，也跳转到首页
          router.push('/')
        }
    } else {
      message.error(response.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录错误:', error)
    message.error(error.message || '登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 登录失败处理
const handleLoginFailed = (errorInfo: any) => {
  console.log('登录表单验证失败:', errorInfo)
}
</script>

<style scoped>
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  z-index: 1;
}

.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
}

.login-content {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 400px;
  padding: 20px;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 16px;
}

.logo img {
  width: 40px;
  height: 40px;
}

.logo h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-top: 24px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s;
}

.forgot-password:hover {
  color: #764ba2;
}

.login-button {
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.register-link {
  text-align: center;
  margin-top: 24px;
  color: #666;
  font-size: 14px;
}

.register-text {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s;
}

.register-text:hover {
  color: #764ba2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-content {
    max-width: 90%;
    padding: 10px;
  }
  
  .login-card {
    padding: 24px;
  }
  
  .logo h1 {
    font-size: 24px;
  }
}

/* 表单项样式优化 */
:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #333;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s;
}

:deep(.ant-input-affix-wrapper:focus),
:deep(.ant-input-affix-wrapper-focused) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

:deep(.ant-checkbox-wrapper) {
  font-size: 14px;
}
</style>